package com.apiserver.data.service;


import com.apiserver.data.dao.BaseMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.lang.reflect.ParameterizedType;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author feizhou
 * @Description 基本方法封装
 * @Date 下午 10:19 2019/10/10 0010
 * @Param
 * @return
 **/

@Slf4j
public abstract class BaseServiceImpl<D extends BaseMapper<M>, M> implements BaseService<M> {


    protected D dao;

    @Autowired
    public void setDao(D dao) {
        this.dao = dao;
    }

    private Class<M> entityClass;

    @SuppressWarnings("unchecked")
    @PostConstruct//构造完成执行的方法
    public void init() {
        entityClass = (Class<M>) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[1];

    }


    @Override
    public M selectById(Object id){

        return dao.selectById(entityClass, id);
    }


    @Override
    public List<M> selectAll(M m) {
        return dao.selectAll(m);
    }

    @Override
    public List<M> selectAllOrderBy(M m, LinkedHashMap<String, String> sortMap) {
        return dao.selectAllOrderBy(m, sortMap);
    }


    @Override
    public List<M> selectAllByOtherKey(M m, Map<String, Object> likeQueryMap, Map<String, List<Object>> arrayQueryMap, LinkedHashMap<String, String> sortMap) {
        return dao.selectAllByOtherKey(m, likeQueryMap, arrayQueryMap, sortMap);
    }


    @Override
    public List<M> selectAllByGroup(M m, List<String> groupList, LinkedHashMap<String, String> sortMap) {
        return dao.selectAllByGroup(m, groupList, sortMap);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(M m) {
        return dao.delete(m);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteById(Object id) {
        return dao.deleteById(entityClass, id);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(List<Object> ids) {
        return dao.deleteByIds(entityClass, ids);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateById(M m) {
        return dao.updateById(m);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(M m, Map<String, Object> queryMap) {
        return dao.update(m, queryMap);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(M m) {
        return dao.insert(m);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchInsert(List<M> listm) {
        int i = 0;
        for (M m : listm) {
            i = i + dao.insert(m);
        }
        return i;
    }


}
